package com.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.common.Constants;
import com.example.springboot.entity.Book;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService extends ServiceImpl<BookMapper,Book> {
    @Autowired
    private BookMapper bookMapper;
    public Book addBook(Book book) {
        Book one=getBookInfo(book);
        if(one==null)
            save(book);
        else throw new ServiceException(Constants.CODE_600,"书籍已存在");
        return book;
    }
    public void releaseBook(Long ISBN,Integer num){
//        QueryWrapper<Book> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("ISBN",ISBN);
        List<Book> bookList=bookMapper.findByISBN(ISBN);
        System.out.println(bookList);
        for(Book one:bookList)
        {
            System.out.println(one);
            one.setInventory(one.getInventory()-num);
            bookMapper.update(one);
        }
    }
    private Book getBookInfo(Book book){
        QueryWrapper<Book> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("ISBN",book.getISBN());
        Book one;
        try{
            one=getOne(queryWrapper);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }
}
